package com.gxa.pingan.interceptor;

import com.gxa.pingan.common.ExceptionCode;
import com.gxa.pingan.exception.BusinessException;
import com.gxa.pingan.utils.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author YXQ
 * @date 2021/11/3 10:59
 */
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        // 这里做权限验证的代码
        String requestURI = request.getRequestURI();
        System.out.println("------"+requestURI+"被拦截");
        // 单独对登录放行
        String suffix = "login";
        // 对图片上传放行
        String suffix1 = "upload";
        String suffix2 = "uploads";
        String suffix3 = "importOrderList";
        String suffix4 = "png";
        String suffix5 = "jpeg";
        if (requestURI.endsWith(suffix) || requestURI.endsWith(suffix1) || requestURI.endsWith(suffix2) || requestURI.endsWith(suffix3)){
            System.out.println("------"+requestURI+"被放行");
            return true;
        }
        if (requestURI.endsWith(suffix4) || requestURI.endsWith(suffix5)){
            System.out.println("------"+requestURI+"被放行");
            return true;
        }
        // 验证token
        // 创建session对象
        HttpSession session = request.getSession();
        // 从请求头获取token
        String token = request.getHeader("token");
        System.out.println("------"+"前端token:   "+token);
        // 从session中获取保存的token
        String token1 = (String) session.getAttribute("token");
        System.out.println("------"+"后端token:  "+token1);
        // 先判断token是否为空,再判断token是否一致，如果一致则放行
        if (!StringUtils.isEmpty(token1) && !StringUtils.isEmpty(token) && token1.equals(token)) {
            // 提示信息
            System.out.println("验证token完毕-->嘿！我被放行啦");
            //
            return true;
        } else {
            System.out.println(requestURI+"验证token失败被拦截");
            // 自定义的异常
            throw new BusinessException(ExceptionCode.WRONG_TOKEN);
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
